package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.mapper.SysRoleMapper;
import com.zhentao.model.admin.page.RolePageParam;
import com.zhentao.model.admin.param.SysRoleMenuAddParam;
import com.zhentao.model.admin.rbac.SysPermission;
import com.zhentao.model.admin.rbac.SysRole;
import com.zhentao.model.admin.rbac.SysRolePermission;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.SysPermissionService;
import com.zhentao.service.SysRolePermissionService;
import com.zhentao.service.SysRoleService;
import com.zhentao.utils.UniqueNumberGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lenovo
 * @description 针对表【sys_role(系统角色)】的数据库操作Service实现
 * @createDate 2024-12-26 19:14:23
 */
@Service
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysRolePermissionService rolePermissionService;



    /**
     * @param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 查询角色列表
     * @author 振涛教育_小Q
     * @date 2024/12/31 16:30
     */
    @Override
    public ResponseResult roleList(RolePageParam param) {
        // 分页
        Page<SysRole> page = new Page<>(param.getPageNum(), param.getPageSize());
        this.page(page,
                Wrappers.<SysRole>lambdaQuery()
                        .like(StringUtils.checkValNotNull(param.getRoleName()),
                                SysRole::getName, param.getRoleName()));
        return ResponseResult.okResult(page);
    }

    /**
     * @param sysRole
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 修改角色的基本信息
     * @author 振涛教育_小Q
     * @date 2025/1/1 17:08
     */
    @Override
    public ResponseResult editRole(SysRole sysRole) {
        // 判断参数是否有效
        if (sysRole == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        sysRole.setUpdateTime(new Date());
        boolean flag = updateById(sysRole);
        return flag ? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS) : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * @param param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 对角色进行授权
     * @author 振涛教育_小Q
     * @date 2025/1/1 17:46
     */
    @Override
    @Transactional
    public ResponseResult roleMenuAdd(SysRoleMenuAddParam param) {
        if (param == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 重新定义接受 权限id集合
        List<Integer> menuIds = new ArrayList<>();
        try {
            // 将前端传送的权限id  转换为 list集合 嵌套
            ObjectMapper objectMapper = new ObjectMapper();
            List<List<String>> result = objectMapper.
                    readValue(param.getMenuIds(), objectMapper.getTypeFactory().constructCollectionType(List.class, List.class));
            // 遍历 result
            for (List<String> list : result) {
                for (String id : list) {
                    menuIds.add(Integer.parseInt(id));
                }
            }
//            System.err.println(result);

        } catch (JsonProcessingException e) {
            throw new RuntimeException("转换 menuIds ArrayList error");
        }
        // 对权限中的集合 去重
        List<Integer> distinctMenuIds = menuIds.stream().distinct().collect(Collectors.toList());
//        System.err.println(distinctMenuIds);
        // 根绝pid 查询子菜单下的按钮权限
        // 定义 存储按钮权限id 集合
        List<Integer> btnIds = new ArrayList<>();
        if (distinctMenuIds.size() > 0) {
            for (Integer menuId : distinctMenuIds) {
                List<Integer> permissions = permissionService.list(Wrappers.<SysPermission>lambdaQuery()
                                .eq(StringUtils.checkValNotNull(menuId), SysPermission::getPid, menuId))
                        .stream().map(SysPermission::getId)
                        .map(Integer::parseInt).collect(Collectors.toList());
                // 判断查询来的数据的主键id是否与menuId 一致  如果一致 那么则不获取对应的id
                if (permissions.size() > 0) {
                    for (Integer permission : permissions) {
                        if (!distinctMenuIds.contains(permission)) {
                            btnIds.add(permission);
                        }
                    }
                }
            }
        }
        // 然后将所有处理完的集合，合并为一个大集合
        distinctMenuIds.addAll(btnIds);
        SysRolePermission rolePermission = new SysRolePermission();
        rolePermission.setRoleId(param.getRoleId());
        rolePermission.setCreateTime(new Date());
        // 遍历权限id集合
        for (Integer menuId : distinctMenuIds) {
            // 判断该用户是否已经有了该权限  有则添加没有 就不添加了
            SysRolePermission permissionServiceOne = rolePermissionService.getOne(Wrappers.<SysRolePermission>lambdaQuery()
                    .eq(StringUtils.checkValNotNull(menuId),
                            SysRolePermission::getPermissionId, menuId)
                    .eq(StringUtils.checkValNotNull(param.getRoleId()),
                            SysRolePermission::getRoleId,
                            param.getRoleId()));
            if(permissionServiceOne == null){
                rolePermission.setPermissionId(menuId.toString());
                rolePermission.setId(String.valueOf(UniqueNumberGenerator.generateUniqueNumber()));
                // 保存
                rolePermissionService.save(rolePermission);
            }
            log.info("已经具备权限：{}", menuId);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @description  软删除角色
     * @author 振涛教育_小Q
     * @date    2025/1/1 19:10
     * @param id
     * @return com.zhentao.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult deleteRole(String id) {
        if(StringUtils.checkValNull(id)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 根据id删除对应的角色
        boolean flag = this.removeById(id);
        return flag? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS) : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }


}




